package service

import (
	"context"
	"errors"
	"github.com/alomerry/home/core/utils"
	"github.com/alomerry/home/core/validators"
	"github.com/alomerry/home/proto/account"
	"github.com/alomerry/home/service/account/model"
)

func (AccountService) Register(ctx context.Context, req *account.RegisterRequest) (*account.RegisterResponse, error) {
	if err := validators.ValidateRequest(req); err != nil {
		return nil, err
	}

	if req.RePassword != req.Password {
		return nil, errors.New("two passwd not equal")
	}

	_, err := model.CUser.GetByUserName(ctx, req.Account)
	if err != nil {
		return nil, err
	}

	// TODO 使用事务

	user := &model.User{
		Username:    req.Account,
		Password:    utils.Md5(req.Password),
		Status:      model.StatusValid,
		SSex:        model.SexUnknown,
		Description: "注册用户",
		Avatar:      model.DefaultAvatar,
	}

	err = user.Create(ctx)
	if err != nil {
		return nil, err
	}

	// TODO cache user info

	return &account.RegisterResponse{}, nil
}
